#include <iostream>
#include <pthread.h>
#include <string>
#include <unistd.h>

using namespace std;

int tickes = 1000;

pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER ;
pthread_cond_t cond = PTHREAD_COND_INITIALIZER ;//条件变量的静态初始化

void* start_routine(void* args)
{
    string name = static_cast<const char*>(args);

    while(true)
    {
        pthread_mutex_lock(&mutex);
        pthread_cond_wait(&cond,&mutex);

        cout << name << "->" << tickes << endl;
        tickes--;

        pthread_mutex_unlock(&mutex);
    }
}



int main()
{
    pthread_t t[5];
    for(int i = 0 ;i < 5 ;i++)
    {
        char* name = new char[64];
        snprintf(name , 64 , "thread %d",i+1);
        pthread_create(&t[i],nullptr,start_routine , name);
    }

    while(true)
    {
        sleep(1);
        // pthread_cond_signal(&cond);//唤醒一个线程
        pthread_cond_broadcast(&cond);//唤醒该条件变量下的所有线程
        cout << "main thread wakeup one thread..." << endl;

    }

    for(int i = 0 ;i < 5 ;i++)
    {
        pthread_join(t[i],nullptr); 
    }



    return 0;
}